
// 引入User
const {User} = require('../../model/user');
// 引入加密模块
const bcrypt = require('bcrypt');

module.exports = async (req, res) => {
  let data = req.body;
  if(data.email.trim().length == 0 || data.password.trim().length == 0){
    res.status(400).render('admin/error', {
      msg: '邮件账号或者密码错误'
    })
  }else{
    // user is object or null 
    let user = await User.findOne({email: data.email});
    const isValid = await bcrypt.compare(data.password, user.password)
    if(user && isValid){
      // 将用户名存储到session请求对象
      req.session.username = user.username;
      // 将用户角色存储到session请求对象
      req.session.role = user.role;
      req.app.locals.userInfo = user;
      // 对用户的角色进行判断
      if(user.role == 'admin'){
        res.redirect('/admin/user')
      }else {
        
        res.redirect('/home/');
      }
    }else {
      res.status(400).render('admin/error', {
        msg: '邮件账号或者密码错误'
      })
    }
  }
}